package com.analog.vserver.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.analog.vserver.domain.file.QueueMinioEntity;
import com.analog.vserver.utils.FFMpegUtil;

import io.minio.MinioClient;
import lombok.extern.log4j.Log4j2;

@Service
@Log4j2
public class VideoService {

	public void processVideo(QueueMinioEntity qme) {
		log.info("=== start video ===");
		JSONObject json = JSON.parseObject(JSON.toJSONString(qme.getData()));
		String uuid = json.getString("uuid");
		String tem = "tem_video";
		String folder = json.getString("folder");
		String m3u8Foler = uuid;
		File myPath = new File(tem);
		if (!myPath.exists()){
			myPath.mkdir();
		}
		FFMpegUtil.setTemVideoAbsPath(myPath.getAbsolutePath());
		String temFolder = "tem_video" + File.separator + uuid;
		myPath = new File(temFolder);
		myPath.mkdir();
		String destination = temFolder + File.separator + uuid;
		String m3u8Path = temFolder + File.separator + "m3u8";
		myPath = new File(m3u8Path);
		myPath.mkdir();
		try {
			
			MinioClient minioClient = new MinioClient(qme.getUrl(), qme.getAccessKey(), qme.getAecretKey());
			InputStream is = minioClient.getObject(folder, uuid);
		
			//生成临时文件
			writeToLocal(is,destination);
			String tsFile = destination + ".ts";
			//转换为ts
			FFMpegUtil.convetorToTs(destination, tsFile);
			//对文件进行切片
			FFMpegUtil.sliceTsToM3U8(tsFile, m3u8Path);
			//上传到 minio
			boolean isExist = minioClient.bucketExists(m3u8Foler);
			if (!isExist) {
				// Make a new bucket called asiatrip to hold a zip file of photos.
				minioClient.makeBucket(m3u8Foler);
			}
			File file = new File(m3u8Path);		//获取其file对象
			File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
			for(File f:fs){					//遍历File[]数组
				if(!f.isDirectory()) {
					minioClient.putObject(m3u8Foler, f.getName(), f.getAbsolutePath());
				}
			}
			
		} catch (Exception e) {
			log.error(e);
		}finally {
			log.info("=== delete dir : " + temFolder);
			deleteDir(new File(temFolder));
		}
		
	}
	
	 /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * 
     * @param dir
     *            将要删除的文件目录
     * @return
     */
    private static boolean deleteDir(File dir) {
        if (!dir.exists()) return false;
        if (dir.isDirectory()) {
            String[] childrens = dir.list();
            // 递归删除目录中的子目录下
            for (String child : childrens) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) return false;
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

	private void writeToLocal(InputStream is,String destination) throws IOException {
		int index;
		byte[] bytes = new byte[1024];
		try (FileOutputStream downloadFile = new FileOutputStream(destination);){
			while ((index = is.read(bytes)) != -1) {
				downloadFile.write(bytes, 0, index);
				downloadFile.flush();
			}
		}finally {
			is.close();
		}
		
	}

}
